/**
 * @filename:ProorderController Dec 22, 2023
 * @project Wonder Vue Admin Api  1.1.0
 * Copyright(c) 2020 Wonder Co. Ltd. 
 * All right reserved. 
 */
package com.wonder.app.controller;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Date;
import java.util.Map;

import cn.hutool.core.date.DateTime;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.wonder.admin.domain.SysAdmin;
import com.wonder.admin.service.SysAdminService;
import com.wonder.app.domain.PrdTaskQty;
import com.wonder.app.domain.Proorder;
import com.wonder.app.domain.Synbd;
import com.wonder.app.mapper.SynbdDao;
import com.wonder.app.service.ProorderService;
import com.wonder.app.request.ProorderRequest;
import com.wonder.common.exception.CustomException;
import com.wonder.common.utils.DateUtils;
import com.wonder.framework.authorization.CheckAdminToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.wonder.common.common.AjaxMap;
import com.wonder.common.common.AjaxResult;
import com.wonder.common.common.CommonPage;
import com.wonder.common.utils.MessageUtils;
import com.wonder.common.utils.StringUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;

import javax.servlet.http.HttpServletRequest;

/**
 * 
 * <p>说明： 生产订单API接口层</P>
 * @version: 1.1.0
 * @author: Wonder
 * @time    Dec 22, 2023
 *
 */
@Api(tags = "生产订单")
@RestController
@RequestMapping("/app/Proorder")
public class ProorderController {
	
	@Autowired
	private ProorderService proorderService;

	@Autowired
	private CheckAdminToken checkAdminToken;

	@Autowired
	private SysAdminService adminService;

	@Autowired
	private SynbdDao synbdDao;
	
	@ApiOperation(value = "生产订单列表")
	@RequestMapping(value = "/index", method = RequestMethod.POST)
	public Map<String,Object> index(@RequestBody ProorderRequest proorderRequest) {
		Page<Proorder> page = new Page<Proorder>(proorderRequest.getPage(), proorderRequest.getLimit());
		IPage<Proorder> list = proorderService.selectList(proorderRequest, page);
		
		Map<String,Object> retMap=new HashMap<>();
		retMap.put("data",CommonPage.restPage(list));
		
  
		return AjaxMap.success(retMap);
	}
	
	/**
	 * @explain 修改排序开关
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/updateExt")
	@ApiOperation(value = "修改排序开关", notes = "作者：Wonder")
	public AjaxResult<Proorder> updateExt(@RequestBody Proorder entity){
		if (null!=entity) {
			boolean rsg = proorderService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success("system.updateSuccess");
			  }else {
				  return AjaxResult.failed("system.updateFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	
	/**
	 * @explain 添加
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/add")
	@ApiOperation(value = "添加", notes = "作者：Wonder")
	public AjaxResult<Proorder> add(@RequestBody Proorder entity){

		if (null!=entity) {
		    
		    String validate=proorderService.validate(entity,"new");
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);    
			boolean rsg = proorderService.save(entity);
			if (rsg) {
				  return AjaxResult.success("system.insertSuccess");
			  }else {
				  return AjaxResult.failed("system.insertFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	
	/**
	 * @explain 查询对象  <swagger GET请求>
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/getUpdateInfo")
	@ApiOperation(value = "获取生产订单对象", notes = "作者：Wonder")
	public AjaxResult<Proorder> getUpdateInfo(@RequestBody Map<String,Object> map){
	    if(map==null) return AjaxResult.failed("system.parameterError");
		Long id=Long.parseLong(map.get("id").toString());		
		 Proorder proorder=proorderService.getById(id);
		
		if (null!=proorder ) {
			 return AjaxResult.success(proorder);
		}else {
			 return AjaxResult.failed("system.parameterError");
		}
		
	}
	
	/**
	 * @explain 修改
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/update")
	@ApiOperation(value = "修改", notes = "作者：Wonder")
	public AjaxResult<Proorder> update(@RequestBody Proorder entity){
		if (null!=entity) {
		    String validate=proorderService.validate(entity,"update");
		    if(StringUtils.hasText(validate))
		         return AjaxResult.failed(validate);
			boolean rsg = proorderService.updateById(entity);
			if (rsg) {
				  return AjaxResult.success("system.updateSuccess");
			  }else {
				  return AjaxResult.failed("system.updateFailed");
			  }
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
	
	/**
	 * @explain 删除
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/delete")
	@ApiOperation(value = "删除", notes = "作者：Wonder")
	public AjaxResult<Proorder> delete(@RequestBody Map<String,Object> map){
		if(map==null)return AjaxResult.failed("system.parameterError");
		String ids=map.get("id").toString();
		ids=StringUtils.remove(ids, '[');
		ids=StringUtils.remove(ids, ']');
		String[] deleteIds=StringUtils.split(ids, ',');
		List<Long> idList=new ArrayList<>(); 
		for(int i=0;i<deleteIds.length;i++)
		{
			idList.add( Long.parseLong(deleteIds[i].trim()));//整数数组
		}

	    boolean rsg = proorderService.removeBatchByIds(idList);
	    if (rsg) {
		    return AjaxResult.success("system.deleteSuccess");
	    }else {
		   return AjaxResult.failed("system.deleteFailed");
	    }
		
	}
	
	/**
	 * @explain 查看生产订单明细
	 * @param   map 对象参数：id
	 * @return  JsonResult
	 * @author  Wonder
	 */
	@PostMapping("/detail")
	@ApiOperation(value = "获取生产订单对象明细", notes = "作者：Wonder")
	public Object detail(@RequestBody Map<String,Object> map){
	    if(map==null) return AjaxResult.failed("system.parameterError");
		String  billNo = map.get("billNo").toString();
		VtuzxMap data = proorderService.getProorderDetail(billNo);
		if (null!=data ) {
			 return AjaxResult.success(data);
		}else {
			 return AjaxResult.failed("system.parameterError");
		}
		
	}

	/**
	 * 反审核生产订单
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/unAudit")
	@ApiOperation(value = "反审核生产订单", notes = "作者：Wonder")
	public AjaxResult<Boolean> unAudit(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception{
		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		String userName = user.getName();
		if(map==null) return AjaxResult.failed("system.parameterError");
		Long id=Long.parseLong(map.get("id").toString());
		boolean flag = proorderService.unAuditProorder(userName,id);
		return AjaxResult.success(flag);
	}


	/**
	 * 审核生产订单
	 * @param request
	 * @param map
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/audit")
	@ApiOperation(value = "反审核生产订单", notes = "作者：Wonder")
	public AjaxResult<Boolean> audit(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception{
		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		String userName = user.getName();
		if(map==null) return AjaxResult.failed("system.parameterError");
		Long id=Long.parseLong(map.get("id").toString());
		boolean flag = proorderService.auditProorder(userName,id);
		return AjaxResult.success(flag);
	}

	/**
	 * 同步生产订单
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/sync_pro_order")
	@ApiOperation(value = "同步生产订单", notes = "作者：Wonder")
	public void syncProOrder() throws Exception{
		//获取最后一次同步的数据
		QueryWrapper<Synbd> queryWrappersyn = new QueryWrapper<>();
		queryWrappersyn.eq("reloadRes",true);
		queryWrappersyn.eq("Ftype","生产订单");
		queryWrappersyn.orderByDesc("Fsyndate");
		queryWrappersyn.last("Limit 1");
		Synbd lastSynbd = synbdDao.selectOne(queryWrappersyn);
		Date fsyndate = null;
		String endTime = "";
		if(null != lastSynbd){
			//最后一次同步时间
			if (null != lastSynbd.getFsyndate()){
				fsyndate = lastSynbd.getFsyndate();
				endTime = DateUtils.dateToStr(fsyndate, "yyyy-MM-dd HH:mm:ss");
			}
		}

		//开始同步之前创建一个新的同步数据
		Synbd synbd = new Synbd();
		synbd.setReloadStartTime(new Date());
		synbd.setFtype("生产订单");

		try {
			proorderService.syncProOrder(endTime);
			//同步结束修改同步状态
			synbd.setReloadEndTime(new DateTime());
			synbd.setFsyndate(new DateTime());
			synbd.setReloadRes(true);
			synbd.setReloadOrder(false);
			synbd.setReloadMsg("");
			synbdDao.insert(synbd);
		} catch (Exception e){
			synbd.setReloadEndTime(new DateTime());
			synbd.setReloadMsg(e.getMessage());
			synbd.setReloadRes(false);
			synbd.setReloadOrder(false);
			synbdDao.insert(synbd);
			throw new Exception(e.getMessage());
		}
	}

	/**
	 * 获取生产订单列表pda
	 * @param map
	 * @return
	 */
	@ApiOperation(value = "获取生产订单列表pda")
	@ResponseBody
	@PostMapping(value = "/get_pro_order_list_pda")
	public AjaxResult<Map<String,Object>> getProOrderListPda(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception{
		if (null == map){
			return AjaxResult.failed("system.parameterError");
		}
		Map<String,Object> data = proorderService.getProOrderListPda(map);
		if (null != data){
			return AjaxResult.success(data);
		} else {
			return AjaxResult.failed();
		}
	}

	/**
	 * 获取用料清单pda
	 * @param map
	 * @return
	 */
	@ApiOperation(value = "获取用料清单pda")
	@ResponseBody
	@PostMapping(value = "/get_pro_bom_list_pda")
	public AjaxResult<Map<String,Object>> getProBom(HttpServletRequest request,@RequestBody Map<String,Object> map) throws Exception{
		if (null == map){
			return AjaxResult.failed("system.parameterError");
		}
		String taskBillNo = map.get("taskBillNo").toString();
		Map<String,Object> data = proorderService.getProBom(taskBillNo);
		if (null != data){
			return AjaxResult.success(data);
		} else {
			return AjaxResult.failed();
		}
	}

	@ApiOperation(value = "传送带开始扫码")
	@RequestMapping(value = "/start_scan_code", method = RequestMethod.POST)
	public AjaxResult<?> startScanCode(@RequestBody Map<String,Object> map)throws Exception {

		Map<String,Object> data =  proorderService.startScanCode(map);
		return AjaxResult.success(data);
	}

	@ApiOperation(value = "获取传送带扫描的追溯码信息")
	@RequestMapping(value = "/get_scan_code", method = RequestMethod.POST)
	public AjaxResult<?> getScanCode(@RequestBody Map<String,Object> map)throws Exception {

		Map<String,Object> data =  proorderService.getScanCode(map);
		return AjaxResult.success(data);
	}

	@ApiOperation(value = "传送带完成扫码")
	@RequestMapping(value = "/end_scan_code", method = RequestMethod.POST)
	public AjaxResult<?> endScanCode(HttpServletRequest request,@RequestBody Map<String,Object> map)throws Exception {
		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		Long userId = user.getUser_id();
		String userName = user.getName();
		String taskBillNo = map.get("taskBillNo").toString();
		String startTime = map.get("startTime").toString();
		String produceDate = map.get("produceDate").toString();
		String batchNo = map.get("batchNo").toString();
		Boolean res =  proorderService.endScanCode(userId,userName,taskBillNo,startTime,produceDate,batchNo);
		return AjaxResult.success(res);
	}

	@ApiOperation(value = "pda直接入库手动填写数量")
	@RequestMapping(value = "/inStock_pda", method = RequestMethod.POST)
	public AjaxResult<?> inStockPda(HttpServletRequest request,@RequestBody Map<String,Object> map)throws Exception {
		String token = checkAdminToken.getTokenFormRequest(request);
		SysAdmin user = adminService.getAdminByToken(token);
		Long userId = user.getUser_id();
		String userName = user.getName();
		Map<String,Object> header = (Map<String, Object>) map.get("header");
		String produceDate = map.get("produceDate").toString();
		Boolean res =  proorderService.inStockPda(userId,userName,header,produceDate);
		return AjaxResult.success(res);
	}


	/**
	 * @explain 修改工时信息
	 * @param   entity
	 * @return  Boolean
	 * @author  Wonder
	 */
	@PostMapping("/updateWorkTime")
	@ApiOperation(value = "修改", notes = "作者：Wonder")
	public AjaxResult<?> updateWorkTime(@RequestBody VtuzxMap data){
		if (null!=data) {
//			String validate=proorderService.validate(entity,"update");
//			proorderService.updateWorkTime(data );
			return AjaxResult.success();
		}else {
			return AjaxResult.failed("system.parameterError");
		}
	}
}